/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Almacen;

import Atxy2k.CustomTextField.RestrictedTextField;
import Controlador.Bean.Almacen.Almacen;
import Controlador.Service.Almacen.GestionAlmacenes;
import gui.General.Main;
import java.awt.Component;
import java.util.List;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import lib.Validaciones;

/**
 *
 * @author César
 */
public class NuevoAlmacen extends javax.swing.JInternalFrame {

    /**
     * Creates new form NuevoAlmacen
     */
    private TableModel tb;
    int clic=0;
    String selectedId;
    gui.Almacen.GestionAlmacenes gestAlmacenes;
    String id = "";
    String nombre = "";
    String ubicacion = "";
    
    public NuevoAlmacen(gui.Almacen.GestionAlmacenes gA) {
        gestAlmacenes = gA;
        initComponents();
        initComp();
    }

    private void initComp(){
        tb = new TableModel();
        tblAlmacen.setModel(tb);
        txtIdAlmacen.setEditable(false);
        tblAlmacen.setDefaultRenderer(JButton.class, new MiRender());
        tblAlmacen.setDefaultEditor( JButton.class, new MiEditor());
        RestrictedTextField restricted = new RestrictedTextField(txtCapacidad);
        restricted.setLimit(20);
        //restricted.setOnlyNums(true);
        restricted = new RestrictedTextField(txtNombre);
        restricted.setLimit(50);
        //restricted.setOnlyText(true);
    } 
    
    private static NuevoAlmacen myna=null;
    
    public static NuevoAlmacen getInstance(gui.Almacen.GestionAlmacenes gestAlmacen) {
         if(myna == null){
            myna = new NuevoAlmacen(gestAlmacen);    
            Main.getDesktop().add(myna); 
            myna.setVisible(true);
               myna.toFront();           
                    }
                    else{
                        if (myna.isClosed()|| !myna.isVisible()) {
                                myna = new NuevoAlmacen(gestAlmacen); 
                                Main.getDesktop().add(myna);
                                myna.toFront();
                                myna.setVisible(true);
                        }
                        else
                            myna.toFront();
                    }
        
        
        
                return myna;
    }
    
    
    
    
    
    public void filtrar(String id, String nombre, String ubicacion){
        this.id=id;
        this.nombre=nombre;
        this.ubicacion=ubicacion;
        tb.actualizarTabla();
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    
    
    
     class TableModel extends AbstractTableModel{
              
        //Two arrays used for the table data
        String[] columnNames = {"Código", "Nombre", "Descripción"
                        , "Ubicación", "Capacidad", "Eliminar" };
               
         List<Almacen> data = Controlador.Service.Almacen.GestionAlmacenes.obtenerAlmacenes();
        
               
        @Override
        public int getRowCount()
        {
            return data.size();
        }
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {        
            switch(column){
                case 0: return data.get(row).getIdAlmacen();
                case 1: return data.get(row).getNombre();
                case 2: return data.get(row).getDescripcion();  
                case 3: return data.get(row).getUbicacion();
                case 4: return data.get(row).getCapacidad();
                default: return new JButton("Eliminar");
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            if(c!=5){
            return getValueAt(0, c).getClass();
            }else{
                return JButton.class;
            }
        }
        
        @Override
        public boolean isCellEditable(int row, int column)
        {
           return false;
        }
        
        public void actualizarTabla(){
            data = Controlador.Service.Almacen.GestionAlmacenes.filtrarAlmacen(id,nombre,ubicacion);
            fireTableDataChanged();
            id="";
            nombre="";
            ubicacion="";
        }
        
    } 
     
    public class MiRender implements TableCellRenderer {
        // Este metodo indica como debe de pintarse el elemento en la fila row, en la columna column
        // que esta en la tabla table y tiene el color dado por el objeto.
        @Override
        public Component getTableCellRendererComponent(JTable table, Object color, boolean isSelected, boolean hasFocus, int row, int column) {    
            // como el boton y el calendario son componentes esto se vale.
            return (JComponent)table.getValueAt(row, column);
        }
     }
     
     public class MiEditor extends AbstractCellEditor implements TableCellEditor {
         private Boolean currentValue;
         @Override
         public Object getCellEditorValue()
         {
            return currentValue;
         }
         //El editor usara el propio componente. Para que funcione la celda en el modelo debe ser editable.
         @Override
         public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
         {
           return (JComponent) value;// la tabla solo debe tener componentes graficos
         }
     }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        lblUbicacion = new javax.swing.JLabel();
        lblDescripcion = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        lblCapacidad = new javax.swing.JLabel();
        txtCapacidad = new javax.swing.JTextField();
        btnGuardar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtUbicacion = new javax.swing.JTextArea();
        txtIdAlmacen = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        pnlAlmacen = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAlmacen = new javax.swing.JTable();

        setClosable(true);
        setMaximumSize(new java.awt.Dimension(600, 450));
        setMinimumSize(new java.awt.Dimension(600, 450));
        setPreferredSize(new java.awt.Dimension(600, 450));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos del almacén"));

        lblNombre.setText("Nombre");

        lblUbicacion.setText("Ubicación");

        lblDescripcion.setText("Descripción");

        txtDescripcion.setColumns(10);
        txtDescripcion.setLineWrap(true);
        txtDescripcion.setRows(5);
        jScrollPane2.setViewportView(txtDescripcion);

        lblCapacidad.setText("Capacidad");

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        txtUbicacion.setColumns(10);
        txtUbicacion.setLineWrap(true);
        txtUbicacion.setRows(5);
        jScrollPane3.setViewportView(txtUbicacion);

        txtIdAlmacen.setEditable(false);

        jLabel1.setText("IdAlmacén");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lblNombre)
                    .addComponent(lblUbicacion)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtIdAlmacen)
                    .addComponent(txtNombre)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 127, Short.MAX_VALUE))
                .addGap(94, 94, 94)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCapacidad)
                    .addComponent(lblDescripcion))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtCapacidad, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(247, 247, 247))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(148, 148, 148)
                .addComponent(btnGuardar)
                .addGap(18, 18, 18)
                .addComponent(btnLimpiar)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCapacidad)
                            .addComponent(txtCapacidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblDescripcion)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtIdAlmacen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblNombre)
                            .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblUbicacion))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardar)
                    .addComponent(btnLimpiar)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        pnlAlmacen.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        pnlAlmacen.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jScrollPane1.setHorizontalScrollBar(null);

        tblAlmacen.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblAlmacen.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblAlmacenMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblAlmacen);

        pnlAlmacen.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 564, Short.MAX_VALUE)
                    .addComponent(pnlAlmacen, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlAlmacen, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        boolean cantidad = Validaciones.validarRealMg(txtCapacidad.getText());
        if(txtCapacidad.getText().isEmpty()){
            JOptionPane.showMessageDialog(this, "Debe ingresar una capacidad", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(!cantidad){
            JOptionPane.showMessageDialog(this, "Debe ingresar una cantidad", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(txtNombre.getText().isEmpty()){
            JOptionPane.showMessageDialog(this, "Debe ingresar un nombre", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(txtDescripcion.getText().isEmpty()){
            JOptionPane.showMessageDialog(this, "Debe ingresar una descripción", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        if(txtUbicacion.getText().isEmpty()){
            JOptionPane.showMessageDialog(this, "Debe ingresar un ubicación de almacén", "error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int resultado =JOptionPane.showConfirmDialog(this, "¿Desea guardar los cambios?", "Confirmación", JOptionPane.YES_NO_OPTION);
        if(resultado == JOptionPane.YES_OPTION){
            Almacen alm = new Almacen(txtIdAlmacen.getText(), txtNombre.getText(), txtUbicacion.getText(), Double.parseDouble(txtCapacidad.getText()), txtDescripcion.getText(), "1");
            if(txtIdAlmacen.getText().isEmpty()){
                GestionAlmacenes.agregarAlmacen(alm);
            }else{
                GestionAlmacenes.actualizarAlmacenes(alm);
            }
            gestAlmacenes.actualizar();
            txtUbicacion.setText("");
            txtCapacidad.setText("");
            txtDescripcion.setText("");
            txtIdAlmacen.setText("");
            txtNombre.setText("");
            tb.actualizarTabla();
            JOptionPane.showMessageDialog(this, "Se ha guardado correctamente", "Confirmación", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        // TODO add your handling code here:
        txtUbicacion.setText("");
        txtCapacidad.setText("");
        txtDescripcion.setText("");
        txtIdAlmacen.setText("");
        txtNombre.setText("");
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void tblAlmacenMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAlmacenMouseClicked
        // TODO add your handling code here:
        int selectedRowIndex = tblAlmacen.getSelectedRow();
        int selectedColumnIndex = tblAlmacen.getSelectedColumn();
        if(selectedColumnIndex!=5){
            String selectId = (String) tblAlmacen.getValueAt(selectedRowIndex, 0);
            if(clic == 1 && selectedId.compareTo(selectId)==0){
                txtIdAlmacen.setText((String)tblAlmacen.getValueAt(selectedRowIndex, 0));
                txtNombre.setText((String)tblAlmacen.getValueAt(selectedRowIndex, 1));
                txtDescripcion.setText((String)tblAlmacen.getValueAt(selectedRowIndex, 2));
                txtUbicacion.setText(((String)tblAlmacen.getValueAt(selectedRowIndex, 3)).toString());
                txtCapacidad.setText(((Double)tblAlmacen.getValueAt(selectedRowIndex, 4)).toString());
            }else if(clic == 0){
                selectedId = selectId;
                clic++;
            }else{
                clic = 0;
            }
        }else{
            int confirmado = JOptionPane.showConfirmDialog(this,"¿Desea eliminar el producto?");
            if (confirmado == JOptionPane.OK_OPTION){
                int cond = Controlador.Service.Almacen.GestionAlmacenes.eliminarAlmacen((String)tblAlmacen.getValueAt(selectedRowIndex, 0));
                if(cond == 1){
                    JOptionPane.showMessageDialog(this, "El almacén que desea eliminar tiene productos dentro");
                }
                gestAlmacenes.actualizar();
                tb.actualizarTabla();
            }                
        }
    }//GEN-LAST:event_tblAlmacenMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        BuscarAlmacen bAlm = new BuscarAlmacen(this);
        Main.getDesktop().add(bAlm);
        bAlm.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JLabel lblCapacidad;
    private javax.swing.JLabel lblDescripcion;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JLabel lblUbicacion;
    private javax.swing.JPanel pnlAlmacen;
    private javax.swing.JTable tblAlmacen;
    private javax.swing.JTextField txtCapacidad;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JTextField txtIdAlmacen;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextArea txtUbicacion;
    // End of variables declaration//GEN-END:variables
}
